package com.leetcode.partition22;

import java.io.*;

/**
 * @author `RKC`
 * @date 2022/3/4 21:13
 */
public class LC2104子数组范围和_枚举 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        int n = Integer.parseInt(reader.readLine());
        int[] nums = new int[n];
        String[] ss = reader.readLine().split(" ");
        for (int i = 0; i < n; i++) nums[i] = Integer.parseInt(ss[i]);
        writer.write(subArrayRanges(nums) + "\n");
        writer.flush();
    }

    public static long subArrayRanges(int[] nums) {
        long ans = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int maxv = nums[i], minv = nums[i];
            for (int j = i + 1; j < n; j++) {
                maxv = Math.max(maxv, nums[j]);
                minv = Math.min(minv, nums[j]);
                ans += maxv - minv;
            }
        }
        return ans;
    }
}
